/* eslint-disable */
import React, { useState, Fragment, useEffect } from 'react';
import { connect } from 'dva';
import { Table, Card, Button, ConfigProvider } from 'antd';
import styles from './index.less';

import '../../global.css';
import moment from 'moment';
import { formatNoFixed, emptyText, reservedDecimalPlace } from '../../utils/commonUtil';
import Search from './search';
import AddPage from './addPage';
import TablePagination from '../../components/common/TablePagination';
import TreePagination from '../../components/common/TreePagination';
import AttachmentUploadModal from '../../components/common/AttachmentUploadModal';
import style from '../index.css';
import { downloadExcel } from '../../services/home/homeService';
import img from '../../assets/logo-loading.gif';

const Index = props => {
  const { dispatch, overdueModel, globalModel } = props;
  const {
    quotaList, lineTypeList, dataSource, total, currentPage, pageSize, loading, searchData, personalizedColumn, allData, treeColumns, basicId, attachmentUploadModalVisible,
    attachmentUploadModalList, attachmentUploadModalLoading, masterDataCode, ownerShipInstitutionCode, ownerShipInstitution, menuData
  } = overdueModel;
  const { userInfo } = globalModel
  const [showAdd, setShowAdd] = useState(false);
  const [detaileData, setDetaileData] = useState(null);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [list, setList] = useState([])

  const menuProcessing = (value) => {
    let count = menuData.filter(item => item.indexOf(value) !== -1)
    return count.length === 0
  }

  useEffect(() => {
    if (dataSource) {
      let data = dataSource.map(item => {
        item.details = menuProcessing("_details")
        return item
      })
      setList(JSON.parse(JSON.stringify(data)))
    }
  }, [menuData, dataSource])

  const createQutoProps = {
    onReset: () => {
      dispatch({ type: "overdueModel/updateState", payload: { currentPage: 1, searchData: null } });
      dispatch({ type: 'overdueModel/getListDatas', payload: { currentPage: 1, pageSize } });
    },
  };

  const addPageProps = {
    detaileData,
    lineTypeList,
    quotaList,
    masterDataCode,
    ownerShipInstitutionCode,
    edit: menuProcessing("_edit"),
    onCancel: () => {
      setShowAdd(false);
      dispatch({ type: 'overdueModel/getListDatas', payload: { currentPage, pageSize, ...searchData }, });
    },
    onUpload: (record) => {
      dispatch({
        type: "overdueModel/updateState", payload: {
          attachmentUploadModalVisible: true, masterDataCode: record.masterDataEncoding,
          ownerShipInstitution: record.affiliatedInstitutionName, basicId: detaileData.id
        }
      });
      dispatch({ type: 'overdueModel/selectAttachment', payload: { masterDataCode: record.masterDataEncoding, fileTypeCode: "account_adjustment", basicId: detaileData.id } });
    },
  };

  const columns = [
    {
      title: '操作', fixed: true, width: 50, key: 'operate',
      render: (text, record) => (
        <span>
          <Button type="link" size="small" onClick={() => goDetail(record)} disabled={record.details}> 查看 </Button>
        </span>
      ),
    },
    { title: '归属机构', dataIndex: 'affiliatedInstitutionName', key: 'affiliatedInstitutionName', ellipsis: true, },
    { title: '出库通知单号', dataIndex: 'outboundOrderNumber', key: 'outboundOrderNumber', ellipsis: true, },
    { title: '销售订单号', dataIndex: 'orderNumber', key: 'orderNumber', ellipsis: true, },
    { title: '交易方名称', dataIndex: 'counterpartyName', key: 'counterpartyName', ellipsis: true, },
    { title: '主数据编码', dataIndex: 'masterDataEncoding', key: 'masterDataEncoding', ellipsis: true, },
    { title: '邓白氏编码', dataIndex: 'dunsCode', key: 'dunsCode', ellipsis: true },
    {
      title: '发货过账时间', dataIndex: 'outboundTime', key: 'outboundTime', width: 100,
      render: (text, record) => (<span>{text ? moment(text).format('YYYY-MM-DD') : ""}</span>),
    },
    {
      title: '出库金额', dataIndex: 'totalPrice', key: 'totalPrice',
      render: (text, record) => (<span>{text ? formatNoFixed(reservedDecimalPlace(text, 2)) : 0}</span>),
    },
    {
      title: '应收金额', dataIndex: 'overDueAmount', key: 'overDueAmount',
      render: (text, record) => (<span>{text ? formatNoFixed(reservedDecimalPlace(text, 2)) : 0}</span>),
    },
    { title: '交易币种', dataIndex: 'currency', key: 'currency', width: 100 },
    {
      title: '账期起算日', dataIndex: 'paymentDaysZeroDate', key: 'paymentDaysZeroDate', width: 100,
      render: (text, record) => (<span>{text ? moment(text).format('YYYY-MM-DD') : ""}</span>),
    },
    {
      title: '到期日', dataIndex: 'maturityDate', key: 'maturityDate', width: 100,
      render: (text, record) => (<span>{text ? moment(text).format('YYYY-MM-DD') : ""}</span>),
    },
    {
      title: '延期至', dataIndex: 'endDate', key: 'endDate', width: 100,
      render: (text, record) => (<span>{text ? moment(text).format('YYYY-MM-DD') : ""}</span>),
    },
    { title: '调整类型', dataIndex: 'lateTypeName', key: 'lateTypeName', ellipsis: true, },
    { title: '调整原因', dataIndex: 'overdueReasonName', key: 'overdueReasonName', ellipsis: true, },
    { title: '状态', dataIndex: 'approvalStatusName', key: 'approvalStatusName', width: 100, ellipsis: true, },
    { title: '业务员', dataIndex: 'businessPeople', key: 'businessPeople', ellipsis: true, },
  ];

  const tablePaginationProps = {
    total,
    currentPage,
    pageSize,
    onPageChange: (page, size) => {
      dispatch({ type: 'overdueModel/updateState', payload: { loading: true, currentPage: page, pageSize: size }, });
      dispatch({ type: 'overdueModel/getListDatas', payload: { currentPage: page, pageSize: size, ...searchData }, });
    },
    onShowSizeChange: (page, size) => {
      dispatch({ type: 'overdueModel/updateState', payload: { loading: true, currentPage: page, pageSize: size }, });
      dispatch({ type: 'overdueModel/getListDatas', payload: { currentPage: page, pageSize: size, ...searchData }, });
    },
  };

  const goDetail = record => {
    setShowAdd(true);
    setDetaileData(record);
  };

  const onExport = () => {
    let headerNames = [];
    let fieldNames = personalizedColumn;
    let lineWidths = [];
    fieldNames.forEach(item => {
      columns.forEach(i => {
        if (item === i.key) {
          headerNames.push(i.title);
          lineWidths.push(80);
        }
      });
    });
    downloadExcel({ headerNames, fieldNames, lineWidths, map: searchData ? JSON.stringify(searchData) : null, sign: 11 }, '账款调整').then(res => {

    });
  };

  const treePaginationProps = {
    personalizedColumn,
    allData,
    treeColumns,
    customKey: "overdueMgt",
    onPersonalizedColumn: record => {
      dispatch({ type: 'overdueModel/updateState', payload: { personalizedColumn: record } });
    },
  };

  const attachmentUploadModalProps = {
    attachmentUploadModalVisible,
    attachmentUploadModalList,
    attachmentUploadModalLoading,
    ownerShipInstitution,
    fileType: "账款调整",
    fileTypeCode: "account_adjustment",
    userInfo: JSON.parse(userInfo),
    masterDataCode,
    ownerShipInstitutionCode,
    basicId,
    onCancel: () => {
      dispatch({ type: "overdueModel/updateState", payload: { attachmentUploadModalVisible: false } });
    },
    onDownload: (values) => {
      dispatch({ type: "overdueModel/downloadFile", payload: values });
    },
    onDelete: (values) => {
      dispatch({ type: "overdueModel/deleteFileById", payload: { params: values, data: { masterDataCode, fileTypeCode: "account_adjustment", basicId: detaileData.id } } });
    },
    onUpload: (values) => {
      dispatch({ type: "overdueModel/updateState", payload: { attachmentUploadModalLoading: true } });
      dispatch({ type: "overdueModel/uploadFile", payload: { params: values, data: { masterDataCode, fileTypeCode: "account_adjustment", basicId: detaileData.id } } });
    }
  };

  useEffect(() => {
    let list = ['operate'];
    let data = [];
    columns.forEach(item => {
      if (list.indexOf(item.key) > -1) data.push(item);
    });
    personalizedColumn.forEach(item => {
      columns.forEach(i => {
        if (item == i.key) data.push(i);
      });
    });
    setCheckedKeys(data);
  }, [personalizedColumn]);

  return (

    <div className={style.roomDiv}>
      {showAdd ? (
        <AddPage {...addPageProps} />
      ) : (
        <Fragment>
          <Search {...createQutoProps} />
          <Card>
            <div className={styles.toolbarText}>
              <div>账款调整列表</div>
              <div style={{ display: 'flex' }}>
                <Button onClick={onExport} disabled={menuProcessing("_down")} > 导出</Button>
                <TreePagination {...treePaginationProps} />
              </div>
            </div>
            <Table
              size="small"
              tableLayout="fixed"
              locale={{ emptyText }}
              columns={checkedKeys}
              dataSource={list}
              pagination={false}
              rowKey={record => record.id}
              loading={
                loading
                  ? {
                    indicator: (
                      <div>
                        <img src={img} alt="" />
                      </div>
                    ),
                  }
                  : false
              }
              scroll={{ x: 2500 }}
            />
            <TablePagination {...tablePaginationProps} />
          </Card>
        </Fragment>
      )
      }
      <AttachmentUploadModal {...attachmentUploadModalProps} />
    </div >

  );
};

function mapStateToProps({ overdueModel, globalModel }) {
  return { overdueModel, globalModel };
}

export default connect(mapStateToProps)(Index);
